package
{
	import flash.system.Security;
	import components.Btn;
	import components.ECGReader;

	import com.google.analytics.AnalyticsTracker;
	import com.google.analytics.GATracker;

	import flash.display.Sprite;
	import flash.events.Event;
	/**
	 * @author perry
	 */
	public class Main extends Sprite
	{
		private var view:ViewSymbol;
		private var ecgReader:ECGReader;
		
		private var tracker:AnalyticsTracker;
		
		private var currentBtn:Btn;
		
		private var examplesData:Array = [  {info:"Normal sinus rhythm recording", url:"http://myweb.msoe.edu/~martynsc/signals/ecg/16773-normalecg.txt"},
											{info:"Partial epilepsy study", url:"http://myweb.msoe.edu/~martynsc/signals/ecg/sz01-epilepsy.txt"},
											{info:"Congestive Heart Failure", url:"http://myweb.msoe.edu/~martynsc/signals/ecg/chf01-heartfailure.txt"} ];
				
		public function Main()
		{
			Security.allowDomain( "http://myweb.msoe.edu/")
			addEventListener(Event.ADDED_TO_STAGE, init );
		}
		
		private function init( e:Event = null ):void
		{
			buildView();
		}
		
		private function buildView():void
		{
			tracker = new GATracker( this, "UA-11448651-6", "AS3", false ); 
			
			view = new ViewSymbol();
			view.warningLabel.text = "";
			view.blocker.visible = false;
			
			addExamples();
			
			ecgReader = new ECGReader();
			ecgReader.addEventListener( ECGReader.COMPLETE, ecgReaderCompleteHandler );
			
			view.ecgReaderContainer.addChild( ecgReader );
			
			addChild( view );
			
			ecgReader.init();
				
			view.blocker.visible = true;
			
			if( !ecgReader.demo )
			{
				ecgReader.loadFile( currentBtn.data.url );
				view.warningLabel.text = "Loading data...";
			}
			else
			{
				ecgReader.loadFile("data/NormalSinusRhythmRecording.txt");
				view.warningLabel.text = "A carregar dados...";
			}
		}
		
		private function addExamples():void
		{
			var b:Btn;
			var i:uint;
			for( i = 0; i < examplesData.length; i++ )
			{
				b = new Btn();
				b.addEventListener( Btn.CLICKED, btnClickedHander );
				b.init( examplesData[i] );
				
				if( i == 0 )
				{
					currentBtn = b;
					currentBtn.select();
				}
				else
				{
					b.y = view.btnsContainer.height + 5;
				}
				
				view.btnsContainer.addChild( b );
			}
		}

		private function ecgReaderCompleteHandler( e:Event ):void
		{
			view.warningLabel.text = "";
			view.blocker.visible = false;
			
//			if( !ecgReader.demo )
//				tracker.trackPageview("/" + currentBtn.data.url);
//			else
//				tracker.trackPageview("/demoHome");
		}

		private function btnClickedHander( e:Event ):void
		{
			currentBtn.unselect();
			
			currentBtn = e.target as Btn;
			
			currentBtn.select();
			
			view.warningLabel.text = "Loading data...";
			view.blocker.visible = true;
			
			ecgReader.loadFile( currentBtn.data.url );
		}
	}
}
